package com.portal.system.mqListener;

import com.portal.common.core.constant.MQConstants;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MessageListener {
//    /**
//     * 处理邮件队列消息
//     * 监听EMAIL_QUEUE队列
//     *
//     * @param message 邮件消息内容
//     * @param channel RabbitMQ通道
//     * @param msg 原始消息对象
//     */
////    @RabbitListener(queues = "${mq.email.queue}")
//    @RabbitListener(queues = MQConstants.EMAIL_QUEUE)
//    public void emailMessageConsumerV1(String message, Channel channel, Message msg) {
//        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
//        try {
//            log.info("收到邮件消息: {}", message);
//            // 处理邮件发送逻辑
//            processEmailMessage(message);
//            // 确认消息已被成功处理
//            channel.basicAck(deliveryTag, false);
//        } catch (Exception e) {
//            log.error("邮件处理失败: {}", e.getMessage(), e);
//            try {
//                // 消息处理失败，拒绝消息并重新入队
//                channel.basicNack(deliveryTag, false, true);
//            } catch (Exception ex) {
//                log.error("消息拒绝失败", ex);
//            }
//        }
//    }


    /**
     * V1和V2两种方法等价
     */

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MQConstants.EMAIL_EXCHANGE, type = ExchangeTypes.TOPIC), // 交换机
            value = @Queue(name = MQConstants.EMAIL_QUEUE), // 队列
            key = MQConstants.EMAIL_ROUTING_KEY // 路由规则
    ))
    public void emailMessageConsumerV2(String message, Channel channel, Message msg) {
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        try {
            log.info("收到邮件消息: {}", message);
            // 处理邮件发送逻辑
            processEmailMessage(message);
            // 确认消息已被成功处理
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("邮件处理失败: {}", e.getMessage(), e);
            try {
                // 消息处理失败，拒绝消息并重新入队
                channel.basicNack(deliveryTag, false, true);
            } catch (Exception ex) {
                log.error("消息拒绝失败", ex);
            }
        }
    }

    private void processEmailMessage(String message) {
        // 实现具体的邮件发送逻辑
        System.out.println(">>>实现具体的邮件发送逻辑<<<");
    }

}
